#ifndef AUTO_HANDLE_H
#define AUTO_HANDLE_H

class AutoHandle
{
public:
	AutoHandle()
		: m_h(NULL)
	{
	}
	AutoHandle(AutoHandle& other)
		: m_h(NULL)
	{
		Attach(other.Detach());
	}
	AutoHandle(HANDLE h)
		: m_h(h)
	{
	}
	~AutoHandle()
	{
		if (m_h != NULL)
		{
			Close();
		}
	}

	void Attach(HANDLE h)
	{
		m_h = h;
	}
	HANDLE Detach()
	{
		HANDLE h = m_h;

		m_h = NULL;

		return h;
	}
	void Close()
	{
		if (m_h != NULL)
		{
			CloseHandle(m_h);
		}
	}

protected:
	bool m_closeHandle;
	HANDLE m_h;
};

#endif